package unittest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import file.LocalSharedFile;
import ftp.MyFtplet;

import junit.framework.TestCase;

public class TestMyFtplet extends TestCase {

	protected void setUp() throws Exception {
		super.setUp();

		makeTestFile();
	}
	
	String file1 = "./src/test/ftp_client.py\n";
	String file2 = "./src/test/mock_server.py\n";
	String file3 = "./src/test/ClientTest.java\n";

	private void makeTestFile() throws FileNotFoundException, IOException {
		BufferedOutputStream bytesOut = new BufferedOutputStream(new FileOutputStream(MyFtplet.published_files));

		bytesOut.write(file1.getBytes());
		bytesOut.write(file2.getBytes());
		bytesOut.close();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		
		deleteTestFile();
	}

	private void deleteTestFile() throws Exception {
		File f = new File(MyFtplet.published_files);
		if(f.exists())
		{
			boolean success = f.delete();
			if(!success)
				throw new Exception("Can not delete file");
		}
	}

	public void testMyFtpletFileExist() {
		MyFtplet ftp = new MyFtplet();
		
		assertEquals(2, ftp.getFiles().size());
	}
	
	public void testMyFtpletFileNotExist() {
		try {
			deleteTestFile();
		} catch (Exception e) {
			fail(e.getMessage());
		}
		
		MyFtplet ftp = new MyFtplet();
		
		assertEquals(0, ftp.getFiles().size());
	}

	public void testAddFile() {
		MyFtplet ftp = new MyFtplet();
		
		ftp.addFile(new LocalSharedFile(file3.trim()));
		
		MyFtplet ftp2 = new MyFtplet();
		
		assertEquals(3, ftp2.getFiles().size());
	}

	public void testRemoveFile() {
		MyFtplet ftp = new MyFtplet();
		
		ftp.removeFile("mock_server.py");
		
		MyFtplet ftp2 = new MyFtplet();
		
		assertEquals(1, ftp2.getFiles().size());
	}
}
